#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <ogcsys.h>

#include "sys.h"

/* Ticket structure */
typedef struct {
	sig_rsa2048 signature;
	tik tik_data;
} ATTRIBUTE_PACKED ticket;

/* Constants */
#define CIOS_TITLEID	(0x100000000ULL | CIOS_VERSION)
#define CIOS_VERSION	249


s32 CIOS_Load(void)
{
	/* Load Custom IOS */
	return IOS_ReloadIOS(CIOS_VERSION);
}

s32 CIOS_IsLoaded(void)
{
	/* Check if Custom IOS is loaded */
	return (IOS_GetVersion() == CIOS_VERSION);
}

s32 CIOS_Identify(void)
{
	static ticket s_tik ATTRIBUTE_ALIGN(32);

	signed_blob *p_certs = NULL, *p_tik = NULL, *p_tmd = NULL, *tick = NULL;
	u32 certs_len, tik_len, tmd_len;

	s32 ret;

	/* Read certificates */
	ret = sys_getcerts(&p_certs, &certs_len);
	if (ret < 0)
		return ret;

	/* Set ticket length */
	tik_len = sizeof(s_tik);

	/* Generate ticket */
	memset(&s_tik, 0, tik_len);
	memset(s_tik.tik_data.cidx_mask, 0xFF, 32);
	strcpy(s_tik.tik_data.issuer, "Root-CA00000001-XS00000003");
	s_tik.signature.type = ES_SIG_RSA2048;

	/* Set ticket pointer */
	p_tik = (signed_blob *)&s_tik;

	/* Retrieve TMD length */
	ret = ES_GetStoredTMDSize(CIOS_TITLEID, &tmd_len);
	if (ret < 0)
		goto out;

	/* Allocate memory */
	p_tmd = (signed_blob *)memalign(32, tmd_len);
	if (!p_tmd) {
		ret = -1;
		goto out;
	}

	/* Retrieve TMD */
	ret = ES_GetStoredTMD(CIOS_TITLEID, p_tmd, tmd_len);
	if (ret < 0)
		goto out;

	/* Identify as system menu */
	ret = ES_Identify(p_certs, certs_len, p_tmd, tmd_len, p_tik, tik_len, NULL);



out:
	/* Free memory */
	if (p_tmd)
		free(p_tmd);
	if (tick)
		free(tick);

	return ret;
}
